using UnityEngine;
using DG.Tweening;
using System;

/// <summary>
/// 贝塞尔曲线（3点）移动策略
/// </summary>
public class BezierMovement : IMovementStrategy
{
    /// <summary>
    /// 贝塞尔曲线高度的系数
    /// </summary>
    private readonly float m_HeightFactor;

    public BezierMovement(float heightFactor = 0.5f)
    {
        m_HeightFactor = Mathf.Clamp(heightFactor, 0.1f, 2f);
    }

    public void Move(GameObject bullet, Vector3 start, Vector3 end, float duration, Action callback)
    {
        // 计算中间控制点（在起点和终点的中间位置上方）
        Vector3 controlPoint = CalculateControlPoint(start, end);

        // 使用二次贝塞尔曲线公式：B(t) = (1-t)2P₀ + 2(1-t)tP₁ + t2P₂
        DOTween.To(t => {
            bullet.transform.position = CalculateBezierPoint(t, start, controlPoint, end);
        },
            0, 1, duration)
            .SetEase(Ease.Linear)
            .OnComplete(() => callback?.Invoke());
    }

    private Vector3 CalculateControlPoint(Vector3 start, Vector3 end)
    {
        // 计算水平中点
        Vector3 midpoint = (start + end) / 2;

        // 计算垂直偏移量（基于起点到终点的距离）
        float distance = Vector3.Distance(start, end);
        //Vector3 direction = (end - start).normalized;

        //// 计算垂直方向，垂直于移动方向
        //Vector3 vertical = Vector3.Cross(direction, Vector3.forward);
        //if (vertical.magnitude < 0.1f) // 如果方向与Z轴平行，使用另一个方向
        //    vertical = Vector3.Cross(direction, Vector3.up);

        //return midpoint + vertical.normalized * (distance * m_HeightFactor);

        return midpoint + Vector3.up * distance * m_HeightFactor;
    }

    private Vector3 CalculateBezierPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2)
    {
        float u = 1 - t;
        return u * u * p0        // (1-t)2 * P₀
               + 2 * u * t * p1  // 2(1-t)t * P₁
               + t * t * p2;     // t2 * P₂
    }
}